#include"List.h"
void LTPrint(LTNode* phead) {
	LTNode* pcur = phead->next;
	while (pcur!=phead) {
		printf("%d->",pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
}

LTNode* LTBuyNode(LTDataType val)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL) {
		perror("malloc fail!!");
		exit(1);
	}
	newnode->next = newnode;
	newnode->prev = newnode;
	newnode->val = val;
}
void LTInit(LTNode** pphead) {
	*pphead = LTBuyNode(-1);
}

void LTPushBack(LTNode* phead, LTDataType val) {
	assert(phead);
	LTNode* newnode = LTBuyNode(val);
	newnode->next = phead;
	newnode->prev = phead->prev;

	phead->prev->next = newnode;
	phead->prev = newnode;
}

void LTPushFront(LTNode* phead, LTDataType val) {
	assert(phead);
	LTNode* newnode = LTBuyNode(val);
	newnode->next = phead->next;
	newnode->prev = phead;

	phead->next->prev = newnode;
	phead->next = newnode;
}

void LTPopBack(LTNode* phead) {
	assert(phead);
	assert(phead->next!=phead);
	LTNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}

void LTPopFront(LTNode* phead) {
	assert(phead);
	assert(phead->next != phead);
	LTNode* del = phead->next;
	phead->next = del->next;
	del->next->prev = phead;
	free(del);
	del = NULL;
}

LTNode* LTFind(LTNode* phead, LTDataType val) {
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead) {
		if (pcur->val == val) {
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void LTInsert(LTNode* pos, LTDataType val) {
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* newnode = LTBuyNode(val);
	
	newnode->next = pos;
	newnode->prev = prev;

	prev->next = newnode;
	pos->prev = newnode;
}
void LTInsertAfter(LTNode* pos, LTDataType val) {
	assert(pos);
	LTNode* next = pos->next;
	LTNode* newnode = LTBuyNode(val);

	newnode->next = next;
	newnode->prev = pos;

	pos->next = newnode;
	next->prev = newnode;
}
void LTErase(LTNode* phead, LTNode* pos) {
	assert(phead->next!=phead);
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}
void LTDestroy(LTNode** pphead) {
	LTNode* pcur = (*pphead)->next;
	LTNode* next = pcur->next;
	while (pcur != *pphead) {
		free(pcur);
		pcur = next;
		if(next!=*pphead)
			next = next->next;
	}
	free(*pphead);
	*pphead = NULL;
}
